package oop.ex4.crosswords;

import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;


/**
 * Basic implementation of dictionary based on an HashMap.
 * @author Dima
 *
 */
public class MyCrosswordDictionary implements CrosswordDictionary {

	///////////////////////////////////////////////////////
	//////////////////////Data Members/////////////////////
	///////////////////////////////////////////////////////
	
	/**
	 * The dictionary.
	 */
	protected Map<String, String> _data; 
	
	///////////////////////////////////////////////////////
	//////////////////////Constructors/////////////////////
	///////////////////////////////////////////////////////
	
	/**
	 * Default constructor, creates an empty dictionary.
	 */
	public MyCrosswordDictionary (){
		_data = new HashMap<String, String>();
	}
	
	/**
	 * Constructs a new MyCrosswordDictionary using a dictionary file.
	 * @param dictionaryFileName The dictionary file. 
	 * @throws IOException On any I/O error trying to access the file.
	 */
	public MyCrosswordDictionary (String dictionaryFileName) throws IOException{
		this();
		load(dictionaryFileName);
	}
	
	///////////////////////////////////////////////////////
	/////////////////////Public Methods////////////////////
	///////////////////////////////////////////////////////
	
	@Override
	public String getTermDefinition(String term) {
		return _data.get(term);
	}

	@Override
	public Set<String> getTerms() {
		return _data.keySet();
	}

	@Override
	public void load(String dictionaryFileName) throws IOException {
		HashSet<String> glosCheck=new HashSet<String>();
		int counter = 1;
		String word, glos;
		Scanner sc = null;
		String regex = "[a-zA-Z\\-]*";
		try {
			sc = new Scanner(new FileReader(dictionaryFileName));
			while (sc.hasNextLine()) {
				String entryLine = sc.nextLine();
				if (entryLine.indexOf(':') != -1) {
					word = entryLine.substring(0, entryLine.indexOf(':'));
					if (word.length()<2 || !word.matches(regex)) continue;
					glos = entryLine.substring(entryLine.indexOf(':') + 1);
					// Adding stars to repetitive glosses for convenience
					// if you implement your dictionary you don't have to do it
					while (glosCheck.contains(glos)) glos+="*";
					glosCheck.add(glos);
				} else {
					// Handling gloss-less files, you don't have to do it
					// If there is no ":" all glosses represented as numbers
					word = entryLine;
					glos = "Dummy" + counter;
				}
				// Ignoring repetitive terms
				_data.put(word.toLowerCase(), glos);
				counter++;
			}
		} finally {
			if (sc != null)
				sc.close();
		}
	}
}
